<template>
  <div class="home-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <div class="search-container">
        <Icon name="search" class="search-icon" />
        <input 
          type="text" 
          placeholder="搜索内容、用户或话题" 
          class="search-input" 
          v-model="searchKeyword"
          @keyup.enter="handleSearch"
          ref="searchInput"
        />
        <button v-if="searchKeyword" class="clear-btn" @click="clearSearch">×</button>
      </div>
    </div>

    <!-- 分类选项卡 -->
    <div class="category-tabs">
      <div class="tabs-wrapper">
        <button 
          v-for="category in categories" 
          :key="category.id" 
          :class="['tab-btn', { active: activeCategory === category.id }]"
          @click="handleCategoryClick(category.id)"
        >
          {{ category.name }}
        </button>
      </div>
    </div>

    <!-- 主内容区域 - 瀑布流布局的信息流 -->
    <main class="content-area" ref="contentRef" @scroll="handleScroll">
      <van-pull-refresh v-model="state.isRefresh" @refresh="onRefresh">
      <!-- 瀑布流动态列布局 -->
      <div class="waterfall-layout" :style="{ '--column-count': columnCount }">
        <div v-for="(column, index) in postColumns" :key="index" class="waterfall-column">
          <!-- 帖子卡片 -->
          <div v-for="post in column" :key="post.entryId" class="post-card" @click="handlePostClick(post)">
            <!-- 用户信息 -->
            <div class="user-info">
              <img :src="post.publisher.avatar" alt="用户头像" class="avatar" />
              <span class="username">{{ post.publisher.username }}</span>
            </div>

            <!-- 帖子内容 -->
            <div class="post-content">
              <!-- 无图片帖子只显示标题 -->
              <h3 v-if="!post.entriesPic" class="post-title-only">{{ post.entryName }}</h3>
              
              <!-- 有图片帖子 -->
              <div v-else>
                <!-- 帖子图片 -->
                <div class="post-image-container">
                  <img 
                    :src="post.entriesPic" 
                    alt="帖子图片" 
                    class="post-image" 
                  />
                </div>
                <!-- 帖子标题 -->
                <h3 class="post-title">{{ post.entryName }}</h3>
              </div>
            </div>

            <!-- 帖子互动数据 -->
            <div class="post-stats">
              <div class="stat-item">
                <Icon name="like-o" /> 
                <span>{{ post.likes }}</span>
              </div>
              <div class="stat-item">
                <Icon name="star-o" /> 
                <span>{{ post.collects }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载更多指示器 -->
      <div v-if="state.isLoading" class="loading-indicator">
        <Loading type="spinner" />加载中...
      </div>
      
      <!-- 搜索结果为空时显示 -->
      <div v-if="!state.isLoading && postColumns.length > 0 && postColumns[0].length === 0" class="empty-result">
        <Icon name="search" size="48" class="empty-icon" />
        <p>暂无相关内容</p>
        <p class="empty-hint">换个关键词试试吧</p>
      </div>
      </van-pull-refresh>
    </main>

    <!-- 底部导航栏 -->
    <tabbar/>
  </div>
</template>

<script setup lang="ts">
import tabbar from '@/components/tab-bar.vue'
import { ref, onMounted, watch, onBeforeUnmount, reactive, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { Icon, Loading, PullRefresh } from 'vant';
import axios from '../utils/axios';

const router = useRouter();
const route = useRoute();

// 帖子列表数据
const entriesList = ref([]);
const searchInput = ref(null);
const contentRef = ref(null);
const columnCount = ref(2);
const postColumns = ref([]);

// 搜索相关数据
const searchKeyword = ref('');
const showSearchBar = ref(true);
const lastScrollTop = ref(0);

// 分类相关数据
const categories = [
  { id: '1', name: '词条' },
  { id: '2', name: '帖子' }
];
const activeCategory = ref('1');

// 状态管理
let state = reactive({
  isRefresh: false,
  isLoading: false,
  finished: false,
  count: 1,
});

const data = reactive({
  page: 1,
  limit: 10,
});

// 清理数据中的URL格式问题
const cleanPostData = (post) => {
  const cleanedPost = { ...post };
  
  if (cleanedPost.entriesPic && typeof cleanedPost.entriesPic === 'string') {
    cleanedPost.entriesPic = cleanedPost.entriesPic.trim().replace(/`/g, '');
  }
  
  if (cleanedPost.publisher && cleanedPost.publisher.avatar && typeof cleanedPost.publisher.avatar === 'string') {
    cleanedPost.publisher.avatar = cleanedPost.publisher.avatar.trim().replace(/`/g, '');
  }
  
  return cleanedPost;
};

// 监听帖子数据和列数变化，重新分割帖子
watch([entriesList, columnCount], () => {
  console.log('更新帖子列表数据:', entriesList.value);
  console.log('列数:', columnCount.value);
  
  postColumns.value = Array.from({ length: columnCount.value }, () => []);
  
  if (entriesList.value && entriesList.value.length > 0) {
    entriesList.value.forEach((post, index) => {
      const cleanedPost = cleanPostData(post);
      const columnIndex = index % columnCount.value;
      postColumns.value[columnIndex].push(cleanedPost);
    });
    console.log('分割后的瀑布流数据:', postColumns.value);
  } else {
    console.log('没有帖子数据可显示');
  }
}, { immediate: true });

// 监听窗口大小变化，动态调整列数
const updateColumnCount = () => {
  const width = window.innerWidth;
  if (width <= 375) {
    columnCount.value = 1;
  } else if (width <= 768) {
    columnCount.value = 2;
  } else if (width <= 1024) {
    columnCount.value = 3;
  } else {
    columnCount.value = 4;
  }
};

// 搜索函数
const handleSearch = () => {
  if (!searchKeyword.value.trim()) return;
  
  // 重置状态
  data.page = 1;
  state.finished = false;
  state.isLoading = true;
  entriesList.value = [];
  
  // 根据当前分类选择搜索方式
  if (activeCategory.value === '1') {
    searchEntries(searchKeyword.value.trim());
  } else {
    searchPosts(searchKeyword.value.trim());
  }
};

// 搜索词条内容
const searchEntries = (keyword) => {
  const currentPage = data.page; // 保存当前页码，避免多次增加
  axios.post("/api/entries/searchEntry", {
    keyword: keyword,
    page: currentPage,
    limit: data.limit,
  })
    .then(res => {
      console.log('词条搜索结果:', res);
      // 处理返回的数据 - 支持直接数组或包含records字段的对象
      const results = Array.isArray(res) ? res : (res && res.records ? res.records : []);
      
      if (results.length > 0) {
        entriesList.value = entriesList.value.concat(results);
        // 确保只增加一次页码
        if (data.page === currentPage) {
          data.page++;
        }
      } else {
        state.finished = true;
      }
      state.isLoading = false;
      if (state.isRefresh) {
        state.isRefresh = false;
      }
    })
    .catch(err => {
      console.error('词条搜索失败:', err);
      state.isLoading = false;
      if (state.isRefresh) {
        state.isRefresh = false;
      }
    });
};

// 搜索帖子内容
const searchPosts = (keyword) => {
  const currentPage = data.page; // 保存当前页码，避免多次增加
  axios.post("/api/entries/searchHot", {
    keyword: keyword,
    page: currentPage,
    limit: data.limit,
  })
    .then(res => {
      console.log('帖子搜索结果:', res);
      // 处理返回的数据 - 支持直接数组或包含records字段的对象
      const results = Array.isArray(res) ? res : (res && res.records ? res.records : []);
      
      if (results.length > 0) {
        entriesList.value = entriesList.value.concat(results);
        // 确保只增加一次页码
        if (data.page === currentPage) {
          data.page++;
        }
      } else {
        state.finished = true;
      }
      state.isLoading = false;
      if (state.isRefresh) {
        state.isRefresh = false;
      }
    })
    .catch(err => {
      console.error('帖子搜索失败:', err);
      state.isLoading = false;
      if (state.isRefresh) {
        state.isRefresh = false;
      }
    });
};

// 刷新函数
const onRefresh = () => {
  state.isRefresh = true;
  state.count = 1;
  state.finished = false;
  data.page = 1;
  
  if (searchKeyword.value.trim()) {
    handleSearch();
  } else {
    // 如果没有搜索关键词，加载默认数据
    entriesList.value = [];
    if (activeCategory.value === '1') {
      searchEntries('');
    } else {
      searchPosts('');
    }
  }
};

// 处理滚动加载更多
const handleScroll = () => {
  if (!contentRef.value || state.isLoading || state.finished) return;
  
  const { scrollTop, scrollHeight, clientHeight } = contentRef.value;
  
  if (scrollTop + clientHeight >= scrollHeight - 100) {
    state.isLoading = true;
    
    if (activeCategory.value === '1') {
      searchEntries(searchKeyword.value.trim());
    } else {
      searchPosts(searchKeyword.value.trim());
    }
  }
};

// 处理分类点击
const handleCategoryClick = (categoryId: string) => {
  if (activeCategory.value === categoryId) return;
  
  activeCategory.value = categoryId;
  // 重置页码和状态
  data.page = 1;
  state.finished = false;
  entriesList.value = [];
  
  // 根据新分类搜索
  if (searchKeyword.value.trim()) {
    handleSearch();
  } else {
    // 如果没有搜索关键词，加载默认数据
    if (categoryId === '1') {
      searchEntries('');
    } else {
      searchPosts('');
    }
  }
};

// 处理帖子点击
const handlePostClick = (post) => {
  // 导航到详情页时，携带当前的搜索关键词作为路由参数
  // 这样当用户返回时，我们可以恢复正确的搜索状态
  router.push({
    name: 'entry',
    query: {
      entryData: JSON.stringify(post),
      searchKeyword: searchKeyword.value, // 传递当前搜索关键词
      searchCategory: activeCategory.value // 传递当前分类
    }
  });
};

// 清空搜索
const clearSearch = () => {
  searchKeyword.value = '';
  // 聚焦到输入框
  nextTick(() => {
    searchInput.value?.focus();
  });
};

// 组件挂载时执行
onMounted(() => {
  updateColumnCount();
  window.addEventListener('resize', updateColumnCount);
  
  // 聚焦到搜索框
  nextTick(() => {
    searchInput.value?.focus();
  });
});

// 监听路由参数变化，确保从其他页面返回时显示正确的搜索结果
watch(() => route.query, (newQuery, oldQuery) => {
  // 检查是否有从详情页返回的特定参数
  if (newQuery.searchKeyword && typeof newQuery.searchKeyword === 'string') {
    // 重置页码和状态
    data.page = 1;
    state.finished = false;
    state.isLoading = true;
    entriesList.value = [];
    
    searchKeyword.value = newQuery.searchKeyword;
    // 如果有分类参数，也一并恢复
    if (newQuery.searchCategory && typeof newQuery.searchCategory === 'string') {
      activeCategory.value = newQuery.searchCategory;
    }
    // 自动执行搜索
    handleSearch();
  } else if (newQuery.keyword && typeof newQuery.keyword === 'string' && 
             newQuery.keyword !== oldQuery?.keyword) {
    // 处理从首页或其他地方跳转过来的情况
    // 重置页码和状态
    data.page = 1;
    state.finished = false;
    state.isLoading = true;
    entriesList.value = [];
    
    searchKeyword.value = newQuery.keyword;
    // 自动执行搜索
    handleSearch();
  } else if (!newQuery.keyword && !newQuery.searchKeyword && !searchKeyword.value.trim() && !entriesList.value.length) {
    // 没有关键词时加载默认数据 - 重置状态
    data.page = 1;
    state.finished = false;
    state.isLoading = true;
    entriesList.value = [];
    
    searchEntries('');
  }
}, { immediate: true, deep: true });

// 组件卸载前移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('resize', updateColumnCount);
});
</script>

<style scoped>
/* 整体容器样式 */
.home-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  margin: 0;
  padding: 0;
  padding-bottom: 60px;
  box-sizing: border-box;
  background-color: #f8f8f8;
}

/* 搜索栏 */
.search-bar {
  position: fixed;
  top: 0;
  background-color: white;
  z-index: 100;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  width: 100%;
  box-sizing: border-box;
}

.search-container {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 20px;
  padding: 8px 16px;
  height: 40px;
  box-sizing: border-box;
  max-width: 500px;
  margin: 0 auto;
}

.search-icon {
  font-size: 18px;
  color: #999;
  margin-right: 8px;
}

.search-input {
  flex: 1;
  border: none;
  background: none;
  outline: none;
  font-size: 14px;
  color: #333;
  height: 100%;
}

.search-input::placeholder {
  color: #999;
}

.clear-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  padding: 0;
  margin-left: 8px;
}

/* 分类选项卡 */
.category-tabs {
  margin-top: 64px; /* 为固定的搜索栏留出空间 */
  background-color: white;
  border-bottom: 1px solid #f0f0f0;
}

.tabs-wrapper {
  display: flex;
  justify-content: center;
  padding: 0 16px;
}

.tab-btn {
  padding: 12px 24px;
  background: none;
  border: none;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  position: relative;
}

.tab-btn.active {
  color: #ff4757;
}

.tab-btn.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 2px;
  background-color: #ff4757;
}

/* 内容区域 */
.content-area {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

/* 瀑布流布局 */
.waterfall-layout {
  display: grid;
  grid-template-columns: repeat(var(--column-count), 1fr);
  gap: 12px;
}

.waterfall-column {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 帖子卡片 */
.post-card {
  background-color: white;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

/* 用户信息 */
.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 8px;
}

.username {
  font-size: 12px;
  color: #666;
}

/* 帖子内容 */
.post-content {
  margin-bottom: 12px;
}

.post-title-only {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.post-image-container {
  margin-bottom: 8px;
  overflow: hidden;
  border-radius: 4px;
}

.post-image {
  width: 100%;
  height: auto;
  display: block;
  transition: transform 0.3s;
}

.post-image:hover {
  transform: scale(1.05);
}

.post-title {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 帖子互动数据 */
.post-stats {
  display: flex;
  justify-content: space-between;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.stat-item Icon {
  margin-right: 4px;
}

/* 加载指示器 */
.loading-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}

/* 空结果提示 */
.empty-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  color: #ccc;
  margin-bottom: 16px;
}

.empty-result p {
  margin: 4px 0;
  color: #999;
}

.empty-hint {
  font-size: 12px;
}
</style>